package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.ProductMapper;
import cn.tedu.coolshark.pojo.dto.ProductDto;
import cn.tedu.coolshark.pojo.dto.ProductUpdateDto;
import cn.tedu.coolshark.pojo.entity.Product;
import cn.tedu.coolshark.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

//@RequestMapper修饰类的话 会将里面的内容和方法上面注解里面的内容拼接到一起
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;
    @RequestMapping("/insert")
    public void insert(@RequestBody ProductDto product){
        System.out.println("product = " + product);
//      把dto里面的数据复制到实体类
        Product p = new Product();
        BeanUtils.copyProperties(product,p);
        //设置发布时间
        p.setCreated(new Date());
        //调用mapper的insert方法
        mapper.insert(p);
    }
    @RequestMapping("/select")
    public List<ProductAdminVO>select(){
        return mapper.selectAdmin();
    }
    @RequestMapping("/selectTop")
    public List<ProductTopVO> selectTop(){
        return mapper.selectTop();
    }
    @RequestMapping("/selectIndex")
    public List<ProductIndexVO>selectIndex(){
        return mapper.selectIndex();
    }
    @RequestMapping("/selectById")
    public ProductDetailVO selectById(int id){

        //让浏览量+1
        mapper.addViewCount(id);

        return mapper.selectById(id);
    }
    @Value("${dirPath}")
    private String dirPath;
    @RequestMapping("/delete")
    public void delete(int id){
        //通过id先查询到图片的名称url
        String url = mapper.selectUrlById(id);
        //删除文件
        new File(dirPath+"/"+url).delete();
        //删除数据库里面的数据
        mapper.deleteById(id);
    }
    @RequestMapping("/selectUpdate")
    public ProductUpdateVO selectUpdate(int id){

        return mapper.selectUpdate(id);
    }
    @RequestMapping("/update")
    public void update(@RequestBody ProductUpdateDto product){

        mapper.update(product);
    }

    @RequestMapping("/selectByCid")
    public List<ProductIndexVO> selectByCid(int id){
        return mapper.selectByCid(id);
    }

    @RequestMapping("/selectByWd")
    public List<ProductIndexVO> selectByWd(String wd){
        System.out.println("wd = " + wd);

        return mapper.selectByWd(wd);
    }

}
